package com.ujiuye.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ujiuye.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/jack")
public class JacksonServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method");
        System.out.println("method="+method);
        switch (method){
//            case "arr":arr(req,resp);break;
//            case "javabean":javabean(req,resp);break;
            case "stuList":stuList(req,resp);break;
        }
    }

    private void stuList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        List<Student> studentList=new ArrayList<>();
        studentList.add(new Student(1,"张三","男","2020-12-11","[唱歌,绘画,书法]","12345.jpg"));
        studentList.add(new Student(2,"李四","男","2020-11-11","[唱歌,绘画,陶瓷工艺]","12345.jpg"));
        studentList.add(new Student(3,"李三思","女","2020-12-12","[唱歌,绘画,跳舞]","12345.jpg"));

        ObjectMapper om=new ObjectMapper();
//        String json=om.writeValueAsString(studentList);
//        System.out.println("json="+json);
        PrintWriter pw=resp.getWriter();
        //将java对象转换成JSON格式字符串并写出去
        om.writeValue(pw,studentList);

    }

    private void javabean(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Student student=new Student(1,"张三","男","2020-12-11","[长跑,跳高]","12345.jpg");
        //创建核心解析器
        ObjectMapper om=new ObjectMapper();
        //将java对象转成JSON格式字符串
        String json=om.writeValueAsString(student);
        System.out.println("json="+json);
        PrintWriter pw=resp.getWriter();
        //写出客户端
        pw.print(json);
        pw.close();
    }


    private void arr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] st={"翘脚牛肉","火锅","小郡肝串串","钵钵鸡","麻婆豆腐"};
        //将数组转成JSON格式的字符串
        //jackson的核心对象
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(st);
        System.out.println("json="+json);
        PrintWriter pw=resp.getWriter();
        pw.print(json);
    }
}
